package com.ruoyi.common.convert;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 将时间戳转为
 */
public class LongToDateDeserializer extends JsonDeserializer<Date> {
    @Override
    public Date deserialize(JsonParser p, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        // if (p.isExpectedNumberIntToken()) {
        //     Long time = p.getLongValue();
        //     return new Date(time);
        // }
        try {
            String time = p.getValueAsString();
            return new Date(Long.parseLong(time));
        } catch (Exception e) {
            try {
                DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = format.parse(p.getValueAsString());
                return date;
            } catch (ParseException ex) {
                return null;
            }
        }
    }
}
